// pages/teacher/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    teacherList: [],
    categories: ['全部', '前端开发', '后端开发', '移动开发', '数据分析', '产品设计'],
    currentCategory: 0,
    loading: false,
    hasMore: true,
    pageNum: 1,
    pageSize: 10
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadTeacherList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 检查是否需要刷新讲师关注状态
    const needRefresh = wx.getStorageSync('refreshTeacherList');
    if (needRefresh) {
      this.refreshFollowStatus();
      wx.removeStorageSync('refreshTeacherList');
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      teacherList: [],
      pageNum: 1,
      hasMore: true
    });
    this.loadTeacherList(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreTeachers();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '知汇堂优质讲师推荐',
      path: '/pages/teacher/index'
    };
  },

  /**
   * 切换分类
   */
  switchCategory(e) {
    const index = e.currentTarget.dataset.index;
    if (index !== this.data.currentCategory) {
      this.setData({
        currentCategory: index,
        teacherList: [],
        pageNum: 1,
        hasMore: true
      });
      this.loadTeacherList();
    }
  },

  /**
   * 加载讲师列表
   */
  loadTeacherList(callback) {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    // 模拟API请求
    setTimeout(() => {
      // 生成模拟数据
      const teachers = this.getMockTeachers();
      
      this.setData({
        teacherList: teachers,
        loading: false,
        hasMore: teachers.length >= this.data.pageSize
      });
      
      if (typeof callback === 'function') {
        callback();
      }
    }, 800);
  },

  /**
   * 加载更多讲师
   */
  loadMoreTeachers() {
    if (this.data.loading || !this.data.hasMore) return;
    
    this.setData({
      pageNum: this.data.pageNum + 1,
      loading: true
    });
    
    // 模拟API请求
    setTimeout(() => {
      // 如果是第3页以后，返回空数组，模拟没有更多数据
      let teachers = [];
      if (this.data.pageNum <= 2) {
        teachers = this.getMockTeachers();
      }
      
      if (teachers.length > 0) {
        this.setData({
          teacherList: [...this.data.teacherList, ...teachers],
          loading: false,
          hasMore: teachers.length >= this.data.pageSize
        });
      } else {
        this.setData({
          loading: false,
          hasMore: false
        });
      }
    }, 800);
  },

  /**
   * 获取模拟讲师数据
   */
  getMockTeachers() {
    const teachers = [];
    const category = this.data.categories[this.data.currentCategory];
    const startIndex = (this.data.pageNum - 1) * this.data.pageSize;
    
    // 讲师名称
    const teacherNames = ['张教授', '李老师', '王讲师', '刘老师', '陈教授', '林讲师', '黄老师', '赵教授', '周讲师', '吴老师'];
    
    // 讲师标签
    const tagsByCategory = {
      '全部': [['前端', 'JavaScript', 'Vue'], ['后端', 'Java', 'Spring'], ['移动开发', 'Flutter', 'React Native'], ['数据分析', 'Python', '机器学习'], ['产品设计', 'UI/UX', 'Figma']],
      '前端开发': [['JavaScript', 'Vue', 'React'], ['HTML/CSS', 'TypeScript', '前端工程化'], ['微信小程序', 'Node.js', '前端性能优化']],
      '后端开发': [['Java', 'Spring Boot', '微服务'], ['Python', 'Django', 'Flask'], ['Go', '云原生', '分布式系统']],
      '移动开发': [['Flutter', 'React Native', '跨平台'], ['Android', 'Kotlin', '原生开发'], ['iOS', 'Swift', '移动UI']],
      '数据分析': [['Python', '数据可视化', '机器学习'], ['大数据', 'Hadoop', 'Spark'], ['统计分析', 'R语言', '数据挖掘']],
      '产品设计': [['UI设计', 'Figma', 'Sketch'], ['用户体验', '交互设计', '原型设计'], ['产品思维', '需求分析', '设计系统']]
    };
    
    // 讲师头衔
    const titles = {
      '前端开发': ['资深前端开发工程师', '前端架构师', 'Web前端讲师'],
      '后端开发': ['高级Java工程师', '后端架构师', '服务端开发专家'],
      '移动开发': ['移动开发工程师', 'Flutter专家', '移动端架构师'],
      '数据分析': ['数据科学家', '机器学习工程师', '数据分析师'],
      '产品设计': ['UI/UX设计师', '产品设计专家', '视觉设计师']
    };
    
    for (let i = 0; i < this.data.pageSize; i++) {
      const index = startIndex + i;
      // 最多返回20条数据
      if (index >= 20) break;
      
      // 根据分类筛选
      let teacherCategory = category;
      if (category === '全部') {
        const categoryKeys = Object.keys(titles);
        teacherCategory = categoryKeys[index % categoryKeys.length];
      }
      
      // 随机选择标签
      const tagPool = tagsByCategory[category];
      const tagIndex = index % tagPool.length;
      
      // 随机选择头衔
      const titlePool = titles[teacherCategory] || titles['前端开发'];
      const titleIndex = index % titlePool.length;
      
      const teacher = {
        id: 'T' + (1000 + index),
        name: teacherNames[index % teacherNames.length],
        avatarUrl: `/assets/images/teacher/avatar${(index % 5) + 1}.png`,
        title: titlePool[titleIndex],
        tags: tagPool[tagIndex],
        courseCount: 5 + Math.floor(Math.random() * 15),
        studentCount: 1000 + Math.floor(Math.random() * 9000),
        rating: (4 + Math.random()).toFixed(1),
        isFollowed: Math.random() > 0.7 // 30%的概率已关注
      };
      
      teachers.push(teacher);
    }
    
    return teachers;
  },

  /**
   * 刷新关注状态
   */
  refreshFollowStatus() {
    const followedTeachers = wx.getStorageSync('followedTeachers') || [];
    
    const teacherList = this.data.teacherList.map(teacher => {
      return {
        ...teacher,
        isFollowed: followedTeachers.includes(teacher.id)
      };
    });
    
    this.setData({ teacherList });
  },

  /**
   * 关注/取消关注讲师
   */
  toggleFollow(e) {
    const teacherId = e.currentTarget.dataset.id;
    const index = this.data.teacherList.findIndex(item => item.id === teacherId);
    
    if (index === -1) return;
    
    const isFollowed = this.data.teacherList[index].isFollowed;
    const newStatus = !isFollowed;
    
    // 更新本地状态
    const teacherList = [...this.data.teacherList];
    teacherList[index].isFollowed = newStatus;
    
    this.setData({ teacherList });
    
    // 更新存储
    let followedTeachers = wx.getStorageSync('followedTeachers') || [];
    
    if (newStatus) {
      // 添加关注
      if (!followedTeachers.includes(teacherId)) {
        followedTeachers.push(teacherId);
      }
      wx.showToast({
        title: '已关注',
        icon: 'success'
      });
    } else {
      // 取消关注
      followedTeachers = followedTeachers.filter(id => id !== teacherId);
      wx.showToast({
        title: '已取消关注',
        icon: 'success'
      });
    }
    
    wx.setStorageSync('followedTeachers', followedTeachers);
  },

  /**
   * 查看讲师详情
   */
  viewTeacherDetail(e) {
    const teacherId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/teacher/detail?id=${teacherId}`
    });
  }
})